package com.dmgameclient.common;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

/**
 * @name 图片解析工具类
 * @Descripation <br>
 *               1、把原始图片缩放成指定大小图片。<br>
 *               2、计算缩放因子。<br>
 * @author 樊俊彬
 * @date 2014-9-9
 * @version 1.0
 */
public class BitmapUtils {

	private static final String TAG = "BitmapUtils";

	/**
	 * 把原始图片缩放成指定大小图片
	 * 
	 * @param data
	 * @param reqWidth
	 * @param reqHeight
	 * @return Bitmap
	 */
	public static Bitmap decodeBitmap(byte[] data, int reqWidth, int reqHeight) {
		Log.i(TAG, ">>>解析图片");
		
		final BitmapFactory.Options options = new BitmapFactory.Options();

		// 避免申请内存造成OOM
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeByteArray(data, 0, data.length, options);
		options.inSampleSize = calculateInSampleSize(options, reqWidth,
				reqHeight);

		// 如需反复解码时设置两参数
		options.inPurgeable = true;
		options.inInputShareable = false;

		// 输出实际内容
		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeByteArray(data, 0, data.length, options);
	}

	/**
	 * 计算缩放因子
	 * 
	 * @param data
	 * @param reqWidth
	 * @param reqHeight
	 * @return int
	 */
	public static int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth, int reqHeight) {

		// 默认宽高和缩放比例
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {

			// 选取方向进行缩放
			if (width > height) {
				inSampleSize = Math.round((float) height / (float) reqHeight);
			} else {
				inSampleSize = Math.round((float) width / (float) reqWidth);
			}
		}
		return inSampleSize;
	}
}